package pt.record.model;

import design.patterns.observer.Subject;
import model.IItem;

/**
 * Created by nuno-rafael-figueiredo on 15-03-2014.
 */
public class Match extends Subject implements IItem<Integer> {
    private Team homeTeam;
    private Team guestTeam;
    private Integer homeGoals;
    private Integer guestGoals;
    private String tv;

    public Match() {
    }

    public Team getHomeTeam() {
        return homeTeam;
    }

    public Team getGuestTeam() {
        return guestTeam;
    }

    public Match setHomeTeam(Team homeTeam) {
        this.homeTeam = homeTeam;
        return this;
    }

    public Match setGuestTeam(Team guestTeam) {
        this.guestTeam = guestTeam;
        return this;
    }

    public Match setHomeGoals(String homeGoals) {
        this.homeGoals = parseGoals(homeGoals);
        return this;
    }

    private Integer parseGoals(String goals) {
        try {
            return new Integer(goals);
        } catch (NumberFormatException e) {
            return null;
        }
    }

    public Integer getHomeGoals() {
        return homeGoals;
    }

    public Match setGuestGoals(String guestGoals) {
        this.guestGoals = parseGoals(guestGoals);
        return this;
    }

    public Integer getGuestGoals() {
        return guestGoals;
    }

    public void setTv(String tv) {
        this.tv = tv;
    }

    public String getTv() {
        return tv;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Match match = (Match) o;

        return !(homeTeam != null ? !homeTeam.equals(match.homeTeam) : match.homeTeam != null) && !(guestTeam != null ? !guestTeam.equals(match.guestTeam) : match.guestTeam != null);

    }

    @Override
    public int hashCode() {
        int result = homeTeam != null ? homeTeam.hashCode() : 0;
        result = 31 * result + (guestTeam != null ? guestTeam.hashCode() : 0);
        return result;
    }

    public Match update(Match match) {
        homeGoals = updateGoals(homeTeam, homeGoals, match.homeGoals);
        guestGoals = updateGoals(guestTeam, guestGoals, match.guestGoals);

        return this;
    }

    private int updateGoals(Team team, int before, int after) {
        if (before != after) {
            int goals = after - before;
            for (int i = 0; i < goals; i++) {
                setChanged();
                notifyObservers(new Goal(team));
            }
        }
        return after;
    }

    @Override
    public Integer getKey() {
        return hashCode();
    }

    /**
     * Created by nuno-rafael-figueiredo on 15-03-2014.
     */
    public static class Goal {
        private final Team team;

        public Goal(Team team) {
            this.team = team;
            team.setChangedAndNotifyObservers(this);
        }

        public Team getTeam() {
            return team;
        }
    }
}
